﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MyBet.Helpers;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MyBet
{
	public partial class JoinContest : UserControl
	{
        public class Contest
        {
            public int id;
            public string displayName;

            public override string ToString()
            {
                String translation = Helpers.LangHelper.GetString(displayName);
                if (String.IsNullOrEmpty(translation))
                {
                    return displayName;
                }
                return translation;
            }

        }

        public delegate void JoinContestDelegate();
        public event JoinContestDelegate OnJoinContest;

        ///<summary>
        /// Stores a reference to the collection of contests objects.
        ///</summary>
        protected readonly ObservableCollection<Contest> _contests = new ObservableCollection<Contest>();

		/// <summary>
		/// Constructor
		/// </summary>
		public JoinContest()
		{
			// Required to initialize variables
			InitializeComponent();
            SetCustomContestNameBackground();
            SetCustomContestPasswordBackground();
            JoinButton.IsEnabled = IsJoinButtonOK();
            // Suppress Silverlight right-click menu for clicks on ListBoxItem elements
            SubscriptionList.DataContext = this;
            SubscriptionList.ItemsSource = _contests;
            SubscriptionList.MouseRightButtonDown += delegate(object sender, MouseButtonEventArgs e)
            {
                e.Handled = true;
            };
		}

		/// <summary>
		/// Page is loaded
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
            BusyControl.IsBusy = true;
            BusyControl.BusyContent = Helpers.LangHelper.GetString("WaitingLoad");
            JoinButton.IsEnabled = false;
            if (App.CurrentUser != null)
            {
                JoinServiceReference.JoinServiceClient joinSvc2 = new JoinServiceReference.JoinServiceClient();
                joinSvc2.GetSubscriptionCompleted += new EventHandler<JoinServiceReference.GetSubscriptionCompletedEventArgs>(joinSvc2_GetSubscriptionCompleted);
                joinSvc2.GetSubscriptionAsync(App.CurrentUser.UserId);
            }
		}

        private void DefaultCustomContest_Click(object sender, RoutedEventArgs e)
        {
            BusyControl.IsBusy = true;
            Contest currentContest = ((MenuItem)sender).DataContext as Contest;
            JoinServiceReference.JoinServiceClient joinSvc2 = new JoinServiceReference.JoinServiceClient();
            joinSvc2.SetDefaultCustomContestCompleted += new EventHandler<JoinServiceReference.SetDefaultCustomContestCompletedEventArgs>(joinSvc2_SetDefaultCustomContestCompleted);
            joinSvc2.SetDefaultCustomContestAsync(App.CurrentUser.UserId, currentContest.id);
        }

        void joinSvc2_SetDefaultCustomContestCompleted(object sender, JoinServiceReference.SetDefaultCustomContestCompletedEventArgs e)
        {
            JoinServiceReference.JoinServiceClient joinSvc2 = new JoinServiceReference.JoinServiceClient();
            joinSvc2.GetSubscriptionCompleted += new EventHandler<JoinServiceReference.GetSubscriptionCompletedEventArgs>(joinSvc2_GetSubscriptionCompleted);
            joinSvc2.GetSubscriptionAsync(App.CurrentUser.UserId);   
        }

        void joinSvc2_GetSubscriptionCompleted(object sender, JoinServiceReference.GetSubscriptionCompletedEventArgs e)
        {
            // Vérification qu'il n'y a pas eu d'erreur
            JoinButton.IsEnabled = IsJoinButtonOK();
            BusyControl.IsBusy = false;

            if (e.Error != null)
            {
                ExceptionErrorDialog dlg = new ExceptionErrorDialog("Erreur interne", e.Error.GetType().FullName + "\n" + e.Error.Message, ExceptionErrorDialog.ErrorType.CriticalError);
                dlg.Show();
                JoinButton.IsEnabled = IsJoinButtonOK();
                return;
            }
            else if (e.myFault != null)
            {
                ExceptionErrorDialog dlg = new ExceptionErrorDialog("Erreur interne", e.myFault.FaultType + "\n" + e.myFault.Message, ExceptionErrorDialog.ErrorType.CriticalError);
                dlg.Show();
                JoinButton.IsEnabled = IsJoinButtonOK();
                return;
            }
            else if (e.Result != null)
            {
                _contests.Clear();
                foreach (JoinServiceReference.CustomContestObject item in e.Result)
                {
                    Contest newContest;
                    if ((item._currentRank.HasValue) && (item._currentRank.Value>0))
                    {
                        newContest = new Contest { id = item._id, displayName = String.Format("{0} - Classement : {1}/{2}", item._displayName.Trim(), item._currentRank.Value, item._subscriberCount) };
                        if ((item._isDefaultContest.HasValue) && (item._isDefaultContest.Value==1))
                        {
                            newContest.displayName = String.Format("{0}*", newContest.displayName);
                        }
                        _contests.Add(newContest);
                    }
                    else
                    {
                        newContest = new Contest { id = item._id, displayName = String.Format("{0} - Classement : -/{2}", item._displayName.Trim(), item._currentRank.Value, item._subscriberCount) };
                        if ((item._isDefaultContest.HasValue) && (item._isDefaultContest.Value==1))
                        {
                            newContest.displayName = String.Format("{0}*", newContest.displayName);
                        }
                        _contests.Add(newContest);                    
                    }
                }
            }
        }

		

		/// <summary>
		/// User join a contest
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void JoinButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	BusyControl.IsBusy = true;
            BusyControl.BusyContent = Helpers.LangHelper.GetString("JoinLoad");

            if (App.CurrentUser != null)
            {
                    JoinServiceReference.JoinServiceClient joinSvc = new JoinServiceReference.JoinServiceClient();
                    joinSvc.JoinContestCompleted += new EventHandler<JoinServiceReference.JoinContestCompletedEventArgs>(joinSvc_JoinContestCompleted);
                    joinSvc.JoinContestAsync(App.CurrentUser.UserId, ContestNameText.Text, ContestPassword.Password);
            }

        }

        void joinSvc_JoinContestCompleted(object sender, JoinServiceReference.JoinContestCompletedEventArgs e)
        {
            String message;
            Error dlg;
            
            //currentContest=ContestList.SelectedItem as Contest;
            BusyControl.IsBusy = false;

            switch (e.Result)
            {
                case MyBet.JoinServiceReference.CustomContestObject.JoinContestStatus.Success:
                    message = String.Format(LangHelper.GetString("JoinSuccessMessage"), ContestNameText.Text);
                    dlg = new Error("", message, Error.ErrorType.Info);
                    dlg.Show();
                    OnJoinContest();
                    break;
                case MyBet.JoinServiceReference.CustomContestObject.JoinContestStatus.AlreadySubscribe:
                    message = String.Format(LangHelper.GetString("JoinFailedMessageAlreadySubscribe"), ContestNameText.Text);
                    dlg = new Error("", message, Error.ErrorType.CriticalError);
                    dlg.Show();
                    break;
                case MyBet.JoinServiceReference.CustomContestObject.JoinContestStatus.NotAllowed:
                    message = String.Format(LangHelper.GetString("JoinFailedMessageNotAllowed"), ContestNameText.Text);
                    dlg = new Error("", message, Error.ErrorType.CriticalError);
                    dlg.Show();
                    break;
                case MyBet.JoinServiceReference.CustomContestObject.JoinContestStatus.GeneralFailure:
                    message = String.Format(LangHelper.GetString("JoinFailedMessageGeneralFailure"), ContestNameText.Text);
                    dlg = new Error("", message, Error.ErrorType.CriticalError);
                    dlg.Show();
                    break;
                default:
                    break;
            }

        }


        #region "Custom contest syntax validation"
        private bool IsCustomContestNameOK()
        {
            return (!String.IsNullOrWhiteSpace(ContestNameText.Text) && (ContestNameText.Text.Trim().Length > 6));
        }

        private bool IsCustomContestPasswordOK()
        {
            return (!String.IsNullOrWhiteSpace(ContestPassword.Password) && ContestPassword.Password.Trim().Length > 6);
        }

        private bool IsJoinButtonOK()
        {
            return ((IsCustomContestNameOK()) && (IsCustomContestPasswordOK()));
        }

        private void SetCustomContestNameBackground()
        {
            if (IsCustomContestNameOK())
            {
                ContestNameText.Background = new SolidColorBrush(Colors.White);
            }
            else
            {
                ContestNameText.Background = new SolidColorBrush(MyBet.Class.ImageUtil.HexColor("FAB6B6"));
            }
        }

        private void SetCustomContestPasswordBackground()
        {
            if (IsCustomContestPasswordOK())
            {
                ContestPassword.Background = new SolidColorBrush(Colors.White);
            }
            else
            {
                ContestPassword.Background = new SolidColorBrush(MyBet.Class.ImageUtil.HexColor("FAB6B6"));
            }
        }



        #endregion


        public void UpdateCulture()
        { 
            //JoinButton.Content=LangHelper.GetString("JoinLabel");
            //ContestsText.Text = LangHelper.GetString("SelectContestLabel");
            //JoinContestTitle.Text = LangHelper.GetString("JoinContestTitle");
        }

        private void ContestNameText_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetCustomContestNameBackground();
            JoinButton.IsEnabled = IsJoinButtonOK();
        }

        private void ContestPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            SetCustomContestPasswordBackground();
            JoinButton.IsEnabled = IsJoinButtonOK();
        }

	}
}